package cn.edu.zzuli.wechat.filter;


import cn.edu.zzuli.common.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class LoginHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("{}","过滤器启动");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        if(handlerMethod.hasMethodAnnotation(NoAuth.class)){
            return true;
        }

        String token = request.getHeader("Authorization");
        if(token != null){
            token = token.replace("Bearer ", "");
        }
        boolean verify = JWTUtils.verify(token);
        if (!verify){
            log.info("{}","请求被拦截!");
            return false;
        }
        log.info("{}",token);

        Integer userId = JWTUtils.getUserId(token);
        request.getSession().setAttribute("uid",userId);
        log.info("当前用户id为: {}",userId);
        return true;
    }
}
